/*
 * SDNestedTableViewController
 * @description 本文件提供创建相册指定人不可见选择联系人界面的ViewController
 * @package
 * @author 		***
 * @copyright
 * @version 		1.0
 * @description 本文件提供创建相册指定人不可见选择联系人界面的ViewController
 */

#import "ExampleNestedTablesViewController.h"
#import "PhotoScrollView.h"
#import "AppCommunicationManager.h"
#import "UIImageView+WebCache.h"
#import "ViewController.h"
#import "BanBu_NavigationController.h"
#import "NXButton.h"
#import "TKLoadingView.h"
#import "AppDataManager.h"

@interface ExampleNestedTablesViewController ()
{
    PhotoScrollView *photoScroll;
    float contentSize_width;
    NSMutableArray *pSelected;
    UIButton * ok;
    NSMutableDictionary *perSelectUidDic;
}

@end

@implementation ExampleNestedTablesViewController

//- (id) init
//{
//    if (self = [super initWithNibName:@"SDNestedTableView" bundle:nil])
//    {
//        // do init stuff
//        self.view.backgroundColor = [UIColor whiteColor];
//    }
//    return self;
//}

- (id)initWithChoosedPeople:(NSMutableArray *)selectedArray
{
    if(self = [super init])
    {
        pSelected = [[NSMutableArray alloc] initWithArray:selectedArray];

    }
    return self;
}

-(void)initSelectPeople
{
    if(![pSelected count]) { return; }
//        [ok setTitle:[NSString stringWithFormat:@"%@(%d)",NSLocalizedString(@"确定", nil),pSelected.count] forState:UIControlStateNormal];
    for(NSDictionary *personSelect in pSelected)
    {
        int i =0;
        BOOL isuc = NO;
        NSString *userid = [personSelect valueForKey:@"userid"];
        for(NSDictionary *personAll in _hArr)
        {
            if([userid isEqualToString:[personAll valueForKey:@"userid"]])
            {
                NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:0];
                photoScroll.contentSize = CGSizeMake(contentSize_width, 49);
                [photoScroll addOneWithIndex:indexPath withuface:[personAll valueForKey:@"uface"]];
                [photoScroll setContentOffset:CGPointMake(contentSize_width-280>0?contentSize_width-280:0, 0) animated:YES];
                contentSize_width += 46.5;
                [photoScroll addOneWithIndex:indexPath withuface:[personAll valueForKey:@"uface"]];
                isuc = YES;
                break;
            }
            i++;
        }
        if(isuc){
            continue;
        }
        BOOL jsuc = NO;
        int j = 0;
        for(NSDictionary *personAll in _gArr)
        {
            if([userid isEqualToString:[personAll valueForKey:@"userid"]])
            {
                NSIndexPath *indexPath = [NSIndexPath indexPathForRow:j inSection:1];
                photoScroll.contentSize = CGSizeMake(contentSize_width, 49);
                [photoScroll addOneWithIndex:indexPath withuface:[personAll valueForKey:@"uface"]];
                [photoScroll setContentOffset:CGPointMake(contentSize_width-280>0?contentSize_width-280:0, 0) animated:YES];
                contentSize_width += 41.7;
                jsuc = YES;
                break;
            }
            j++;
        }
        if(jsuc){continue;};
    }
}

-(void)viewDidLoad
{
    [super viewDidLoad];
    BanBu_NavButton *btn_return=[[BanBu_NavButton alloc] initWithButtonType:UIButtonCreatTypeBack];
    btn_return.position = ButtonPositionLeft;
    [btn_return addTarget:self action:@selector(popself) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *bar_itemreturn=[[UIBarButtonItem alloc] initWithCustomView:btn_return];
    self.navigationItem.leftBarButtonItem = bar_itemreturn;
    

    
    self.title = NSLocalizedString(@"choosePerson", 选择联系人);
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(removeOne:) name:@"didselectcell" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(DelaytoPerform) name:@"DismissSelectUser" object:nil];
    [TKLoadingView showTkloadingAddedTo:self.navigationController.view point:self.view.center title:NSLocalizedString(@"loadingNotice", nil ) activityAnimated:YES];
    self.tableView.userInteractionEnabled = NO;
    self.tableView.frame = CGRectMake(0, 0, 320, __MainScreen_Height - 20 - 64);
//    if (IS_IOS_7)
//    {
//        self.tableView.frame = CGRectMake(0, 0, 320, __MainScreen_Height - 20);
//    }
//    else
//    {
//        self.tableView.frame = CGRectMake(0, 0, 320, __MainScreen_Height - 20 - 64);
//    }
    [self GreatSearchBar];
    [AppComManager getBanBuData:BanBu_GetFriendList_transmit par:[NSDictionary dictionaryWithObjectsAndKeys:@"y",@"groupby",nil] delegate:self];
}

-(void)GreatSearchBar//创建SearchBar
{
    self.searchBl = NO;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.allowsSelectionDuringEditing = YES;
    
    self.chooseDic = [NSMutableDictionary dictionaryWithCapacity:20];
    self.pnameDic = [NSMutableDictionary dictionaryWithCapacity:30];
    perSelectUidDic  = [NSMutableDictionary dictionaryWithCapacity:30];
    user_dic = [NSMutableDictionary dictionaryWithCapacity:10];
    if(!pSelected)
    {
        pSelected = [[NSMutableArray alloc] initWithCapacity:0];
    }
    contentSize_width = 45;
//    [self GreatBtn];
    [self bottomView];
    
    //添加SearchBar
    
    //加载搜索框
    self.searchView = [[UISearchBar alloc] initWithFrame:CGRectMake(0.0, 0.0, self.view.bounds.size.width, 40)];
    self.searchView.delegate = self;
    self.searchDisplayCon = [[UISearchDisplayController alloc]initWithSearchBar:self.searchView contentsController:self];
    self.searchDisplayCon.delegate = self;
    self.searchDisplayCon.searchResultsDelegate = self;
    self.searchDisplayCon.searchResultsDataSource = self;
    self.tableView.tableHeaderView = self.searchView;
    [self setEditing:YES animated:YES];

}

-(void)GreatBtn
{
    UIBarButtonItem * cancel = [[UIBarButtonItem alloc]initWithTitle:NSLocalizedString(@"取消", nil) style:UIBarButtonItemStyleDone target:self action:@selector(popself)];
    self.navigationItem.rightBarButtonItem = cancel;
}

-(void)bottomView//添加底部选择框
{
    UIImageView * bottomview = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"select_bar_bg.png"]];
    UIView * botview;
    bottomview.frame = CGRectMake(0, __MainScreen_Height - 22 - 64,320,49);
    photoScroll = [[PhotoScrollView alloc]initWithFrame:CGRectMake(0, __MainScreen_Height - 25 - 64, 320, 49)];
    botview = [[UIView alloc]initWithFrame:CGRectMake(261, __MainScreen_Height-25 - 64, 80, 49)];
//    if (IS_IOS_7)
//    {
//        bottomview.frame = CGRectMake(0, __MainScreen_Height - 22,320,49);
//        photoScroll = [[PhotoScrollView alloc]initWithFrame:CGRectMake(0, __MainScreen_Height - 25, 320, 49)];
//        botview = [[UIView alloc]initWithFrame:CGRectMake(261, __MainScreen_Height-25, 80, 49)];
//    }
//    else
//    {
//        bottomview.frame = CGRectMake(0, __MainScreen_Height - 22 - 64,320,49);
//        photoScroll = [[PhotoScrollView alloc]initWithFrame:CGRectMake(0, __MainScreen_Height - 25 - 64, 320, 49)];
//        botview = [[UIView alloc]initWithFrame:CGRectMake(261, __MainScreen_Height-25 - 64, 80, 49)];
//    }
    [self.view addSubview:bottomview];
    
    
    
    photoScroll.contentSize = CGSizeMake(contentSize_width, 49);
    photoScroll.backgroundColor = [UIColor clearColor];
    [self.view addSubview:photoScroll];
    
    
    botview.backgroundColor = [UIColor clearColor];
    [self.view addSubview:botview];
    
     ok = [UIButton buttonWithType:UIButtonTypeCustom];
    [ok setBackgroundImage:[UIImage imageNamed:@"btn_ok.png"] forState:UIControlStateNormal];
    [ok setTitle:NSLocalizedString(@"确定", nil) forState:UIControlStateNormal];
    [ok addTarget:self action:@selector(CreateGroup) forControlEvents:UIControlEventTouchUpInside];
    ok.titleLabel.font = [UIFont systemFontOfSize:13];
    ok.frame = CGRectMake(0, 9, 50, 30);
    [botview addSubview:ok];
}

#pragma mark - Nested Tables methods

- (NSInteger)mainTable:(UITableView *)mainTable numberOfItemsInSection:(NSInteger)section
{
    //修改：yinlinlin,不显示粉丝2014/06/26
    return 1;
    //搜索
    if ( [mainTable isEqual:self.searchDisplayController.searchResultsTableView] ){
        return 1;
    }else{
        return 2;
    }
}

- (NSInteger)mainTable:(UITableView *)mainTable numberOfSubItemsforItem:(SDGroupCell *)item atIndexPath:(NSIndexPath *)indexPath
{
    if ( [mainTable isEqual:self.searchDisplayController.searchResultsTableView]){
        return self.searchResultArr.count;
    }else{
    return item.groupArray.count;
    }
}

- (SDGroupCell *)mainTable:(UITableView *)mainTable setItem:(SDGroupCell *)item forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([mainTable isEqual:self.searchDisplayController.searchResultsTableView])
    {
        if (self.searchResultArr)
        {
            item.groupArray = self.searchResultArr;
        }else{
        }
        return item;
    }
    else
    {
        if (indexPath.row ==0) {
            item.groupArray = _hArr;
            item.itemText.text = [NSString stringWithFormat:NSLocalizedString(@"summary_h", nil)];
        }else{
            item.groupArray = _gArr;
            item.itemText.text = [NSString stringWithFormat:NSLocalizedString(@"summary_f", nil)];
        }
        return item;
    }
}

-(void)transformDiction:(NSMutableArray *)people
{
    [perSelectUidDic removeAllObjects];
    NSMutableArray *pselectA = [NSMutableArray arrayWithCapacity:0];
    for(BanBu_UserModel *userModel in people)
    {
        [pselectA addObject:[NSDictionary dictionaryWithObjectsAndKeys:userModel.user_id,@"userid",userModel.face_url,@"uface",userModel.pname,@"pname", userModel.gender,@"gender",nil]];
        
        [perSelectUidDic setValue:[NSNumber numberWithBool:YES] forKeyPath:userModel.user_id];
    }
    [pSelected removeAllObjects];
    [pSelected addObjectsFromArray:pselectA];
}

- (SDSubCell *)item:(SDGroupCell *)item setSubItem:(SDSubCell *)subItem forRowAtIndexPath:(NSIndexPath *)indexPath
{
    subItem.itemText.text = [[item.groupArray objectAtIndex:indexPath.row] valueForKey:@"pname"];
    subItem.uface = [[item.groupArray objectAtIndex:indexPath.row] valueForKey:@"uface"];
    subItem.userid = [[item.groupArray objectAtIndex:indexPath.row] valueForKey:@"userid"];
    
    if([perSelectUidDic valueForKey:[[item.groupArray objectAtIndex:indexPath.row] valueForKey:@"userid"]])
    {
        [subItem check];
    }
    return subItem;
}

- (void) mainTable:(UITableView *)mainTable itemDidChange:(SDGroupCell *)item
{
    SelectableCellState state = item.selectableCellState;
    NSIndexPath *indexPath = [self.tableView indexPathForCell:item];
    switch (state) {
        case Checked:
            NSLog(@"Changed Item at indexPath:%@ to state \"Checked\"", indexPath);
            break;
        case Unchecked:
            NSLog(@"Changed Item at indexPath:%@ to state \"Unchecked\"", indexPath);
            break;
        case Halfchecked:
            NSLog(@"Changed Item at indexPath:%@ to state \"Halfchecked\"", indexPath);
            break;
        default:
            break;
    }
}

-(void)removeOne:(NSNotification *)_not
{
    NXButton *btn = [_not object];
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:btn.section inSection:0];
    SDGroupCell *gcell = (SDGroupCell *)[self.tableView cellForRowAtIndexPath:indexPath];
    NSIndexPath *inde = [NSIndexPath indexPathForRow:btn.row inSection:0];
    [gcell tableView:gcell.subTable didSelectRowAtIndexPath:inde];
}

-(void)groupCell:(SDGroupCell *)cell didSelectSubCell:(SDSubCell *)subCell withIndexPath:(NSIndexPath *)indexPath andWithTap:(BOOL)tapped
{
    NSIndexPath *groupCellIndexPath = [self.tableView indexPathForCell:cell];
    NSIndexPath *indexP = [NSIndexPath indexPathForRow:indexPath.row inSection:groupCellIndexPath.row];
    if(subCell.selectableCellState == Checked)
    {
        photoScroll.contentSize = CGSizeMake(contentSize_width, 49);
        [photoScroll addOneWithIndex:indexP withuface:subCell.uface];
        [photoScroll setContentOffset:CGPointMake(contentSize_width-280>0?contentSize_width-280:0, 0) animated:YES];
        contentSize_width += 43.5;
        [pSelected addObject:[cell.groupArray objectAtIndex:indexPath.row]];
    }
    else
    {
        [photoScroll removeOneWithIndex:indexP];
        contentSize_width -= 43.5;
        photoScroll.contentSize = CGSizeMake(contentSize_width, 49);
        [pSelected removeObject:[cell.groupArray objectAtIndex:indexPath.row]];
        [photoScroll setContentOffset:CGPointMake(contentSize_width-280>0?contentSize_width-280:0, 0) animated:YES];
    }

    NSLog(@"%@",pSelected);
    if (pSelected.count > 0){
        ok.enabled = YES;
//        [ok setTitle:[NSString stringWithFormat:@"%@(%d)",NSLocalizedString(@"确定", nil),pSelected.count] forState:UIControlStateNormal];
    }else{
        ok.enabled = NO;
//        [ok setTitle:[NSString stringWithFormat:@"%@",NSLocalizedString(@"确定", nil)] forState:UIControlStateNormal];
    }
}

- (void) item:(SDGroupCell *)item subItemDidChange:(SDSelectableCell *)subItem
{
    SelectableCellState state = subItem.selectableCellState;
    NSIndexPath *indexPath = [item.subTable indexPathForCell:subItem];
    switch (state) {
        case Checked:
            NSLog(@"Changed Sub Item at indexPath:%@ to state \"Checked\"", indexPath);
            break;
        case Unchecked:
            NSLog(@"Changed Sub Item at indexPath:%@ to state \"Unchecked\"", indexPath);
            break;
        default:
            break;
    }
}

- (void)expandingItem:(SDGroupCell *)item withIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"Expanded Item at indexPath: %@", indexPath);
}

- (void)collapsingItem:(SDGroupCell *)item withIndexPath:(NSIndexPath *)indexPath 
{
    NSLog(@"Collapsed Item at indexPath: %@", indexPath);
}

- (void)banbuRequestDidFinished:(NSDictionary *)resDic error:(NSError *)error
{
    NSLog(@"%@",resDic);
    if(error)
    {
        
    }
    else
    {
        if([AppComManager respondsDic:resDic isFunctionData:BanBu_GetFriendList_transmit])
        {
            if([[resDic valueForKey:@"ok"] boolValue])
            {
                [TKLoadingView dismissTkFromView:self.navigationController.view animated:YES afterShow:0];
                self.tableView.userInteractionEnabled = YES;
                _hArr = [resDic valueForKey:@"list_h"];
                _gArr = [resDic valueForKey:@"list_g"];
                [self.tableView reloadData];
                [self transformDiction:pSelected];
                [self initSelectPeople];
                [self transmitArrToDic:self.hArr];
                [self transmitArrToDic:self.gArr];
                ok.enabled = NO;
            }
        }
    }
}

//将姓名转存到姓名资料字典中
-(void)transmitArrToDic:(NSArray *)infoArray
{
    for (NSDictionary * dic in infoArray)
    {
        [self.pnameDic setValue:dic forKey:[dic valueForKey:KeyPname]];
    }
}

#pragma mark - UISearchBarDelegate
- (void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope
{
    NSPredicate *resultPredicate = [NSPredicate predicateWithFormat:@"SELF contains[cd] %@", searchText];
    self.searchResults = [self.pnameDic.allKeys filteredArrayUsingPredicate:resultPredicate];

    self.searchResultArr = [NSMutableArray arrayWithCapacity:self.searchResults.count];
    for (NSString * pName in  self.searchResults)
    {
        NSDictionary * friendInfoDic = [self.pnameDic valueForKey:pName];
        [self.searchResultArr addObject:friendInfoDic];
    }
}

#pragma mark -

-(void)searchDisplayControllerWillBeginSearch:(UISearchDisplayController *)controller
{
    self.searchBl = YES;
    UISearchBar *searchBar = self.searchDisplayController.searchBar;
    [searchBar setShowsCancelButton:YES animated:YES];
}

-(void)searchDisplayController:(UISearchDisplayController *)controller willHideSearchResultsTableView:(UITableView *)tableView
{
    self.searchBl = NO;
    [self.tableView reloadData];
}

-(BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString
{
    [self filterContentForSearchText:searchString scope:[[self.searchDisplayController.searchBar scopeButtonTitles]  objectAtIndex:[self.searchDisplayController.searchBar selectedScopeButtonIndex]]];
    
    return(YES);
}


- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchScope:(NSInteger)searchOption
{
    [self filterContentForSearchText:[self.searchDisplayController.searchBar text] scope:[[self.searchDisplayController.searchBar scopeButtonTitles]objectAtIndex:searchOption]];
    return(YES);
}


-(void)DelaytoPerform
{
    [self performSelector:@selector(popself) withObject:nil afterDelay:1];
}

-(void)popself
{
    [self dismissViewControllerAnimated:YES completion:^{
//    [[NSNotificationCenter defaultCenter] postNotificationName:@"refreshView" object:nil];
    }];
}

-(void)CreateGroup
{
    NSLog(@"%@",pSelected);
    
    //创建新的的分组
    NSMutableArray * selectedArray = [[NSMutableArray alloc]initWithCapacity:10];
    for (NSDictionary * userDict in pSelected)
    {
        BanBu_UserModel * userModel = [[BanBu_UserModel alloc]init];
        userModel.user_id = [userDict valueForKeyPath:@"userid"];
        userModel.face_url = [userDict valueForKey:@"uface"];
        [selectedArray addObject:userModel];
    }
    //如果是更改之前的分组，将修改之后的数据传到上一界面并返回
    if (_changeGroupCallBack)
    {
        _changeGroupCallBack(selectedArray);
        [self dismissViewControllerAnimated:YES completion:nil];
        return;
    }


    ViewController * mvc = [[ViewController alloc]initWithPersonDataArray:selectedArray];
    BanBu_NavigationController * nvc = [[BanBu_NavigationController alloc]initWithRootViewController:mvc];
    [self presentModalViewController:nvc animated:YES];
}

- (void)dealloc
{
//    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"didselectcell" object:nil];
//    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"DismissSelectUser" object:nil];
}

@end
